package com.example.black.myapplication;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

    private List<String> list;
    private List<Integer> heights;
    private Context context;

    public MyAdapter(List<String> list, Context context) {
        this.list = list;
        heights = new ArrayList<>();
        for (String s :
                list) {
            heights.add((int) Math.max(200,Math.random()*550));
        }
        this.context = context;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //View  view = View.inflate(parent.getContext(),R.layout.test_recycle_item,parent);//针对瀑布流由于需要修改 布局参数，使用此种方式，网格布局和单列表布局不会有问题，但是，瀑布流需要在动态修改高度
        View  view = LayoutInflater.from(parent.getContext()).inflate( R.layout.test_recycle_item, parent,false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.tv.setText(
                list.get(position)
        );
       // holder.tv.setBackgroundColor(Color.rgb(100, (int)(Math.random()*255), (int)(Math.random()*255)));
//        ViewGroup.LayoutParams params = holder.tv.getLayoutParams();
//        params.height = heights.get(position);
//        holder.tv.setLayoutParams(params);
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder{
       TextView tv;
        public MyViewHolder(View itemView) {
            super(itemView);
            tv = itemView.findViewById(R.id.tv);
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(context,"item test:"+getAdapterPosition(),Toast.LENGTH_LONG).show();
                }
            });
        }
    }
    public void addData(){
        list.add(0,"拉拉");
        heights.add(0,(int) Math.max(200,Math.random()*550));
        notifyItemInserted(0);
    }
    public void removeData(int position){
        list.remove(position);
        heights.remove(position);
        notifyItemRemoved(position);
    }
}
